using Model.Core.Services;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace RobotClient.Controllers
{
    public class JackDevCtrl
    {
        private readonly ILogger<JackDevCtrl> _logger;
        public JackDevCtrl(IServiceProvider serviceProvider, ILogger<JackDevCtrl> logger)
        {
            _logger = logger;
            LocalMqClientCtrl = serviceProvider.GetService<LocalMqClientCtrl>();
            init();
        }
        public void init()
        {
            _ = LocalMqClientCtrl.AddSubTopic(md_robot_jack_info); //断线重连后重新订阅顶升消息
            LocalMqClientCtrl.MsgReceivedEvent += Robot_Jack_Info_Detail;
        }

        //处理顶升消息
        const string md_robot_jack_info = "md/robot/jack/info";/// 顶升当前状态信息反馈
        const string md_robot_jack_ctrl = "md/robot/jack/ctrl";/// 顶升控制

        public static MyUseQueue<JackStatusType> JackCurStatusEnumQueue = new MyUseQueue<JackStatusType>(5);
        public void Robot_Jack_Info_Detail(string topic, string data)
        {
            if (topic.Equals(md_robot_jack_info))
            {
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        JsonObject? recvobj = JsonSerializer.Deserialize<JsonObject>(data);

                        if (recvobj != null)
                        {
                            string? statusstr = recvobj["value"]?.ToString();
                            if (!string.IsNullOrEmpty(statusstr))
                            {
                                var JackStatusTypenum = Enum.Parse<JackStatusType>(statusstr);
                                JackCurStatusEnumQueue.Enqueue(JackStatusTypenum);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "JSON反序列化失败");
                        return;
                    }
                }
            }

        }

        static int regnum = 0;

        //   public AppMqFactory _AppMqFactory { get; }
        public LocalMqClientCtrl LocalMqClientCtrl { get; }


        // //    void CheckStatus() => CheckStableStatus(targetStatus, regnum, tcs);
        // /// <summary>
        // /// 顶升控制
        // /// </summary>
        // /// <param name="isup">up 为升 down为降 stop停止</param>
        // /// <returns></returns>
        // public async Task<(bool successed, string msg)> Jack_Ctrl_Func(JackCtrlType isup)
        // {
        //     using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        //     regnum = new Random().Next(100, 1000);
        //     _logger.LogInformation("当前顶升控制ID：{JackID}", regnum);

        //     JsonObject keyValuePairs = new JsonObject();
        //     keyValuePairs.Add("type", Enum.GetName(isup)?.ToString());
        //     _ = LocalMqClientCtrl.SendMessageAsync(md_robot_jack_ctrl, keyValuePairs.ToString());

        //     var targetStatus = GetTargetJackStatus(isup);
        //     var tcs = new TaskCompletionSource<bool>();

        //     void CheckStatus() => CheckStableStatus(targetStatus, regnum, tcs);


        //     JackCurStatusEnumQueue.AddHandler(CheckStatus);
        //     CancellationTokenRegistration registration = cts.Token.Register(() =>
        //     {
        //         JackCurStatusEnumQueue.ClearAllSubscriptions();
        //         if (!tcs.Task.IsCompleted)
        //         {
        //             _logger.LogWarning("控制ID[{JackID}]操作超时", regnum);
        //             tcs.TrySetResult(false);
        //         }
        //     });
        //     CheckStatus();
        //     try
        //     {
        //         bool result = await tcs.Task;
        //         return (result, result ? "操作成功" : "操作超时");
        //     }
        //     catch (Exception ex)
        //     {
        //         _logger.LogError(ex, "控制ID[{JackID}]操作异常", regnum);
        //         return (false, $"操作异常: {ex.Message}");
        //     }
        // }

        void CheckStableStatus(JackStatusType targetStatus, int regnum, TaskCompletionSource<bool> tcs)
        {

                try
                {
                    if (JackCurStatusEnumQueue.Count == 0)
                    {
                        _logger.LogWarning("控制ID[{JackID}]状态队列为空，等待数据...", regnum);
                        return;
                    }

                    var queueList = JackCurStatusEnumQueue.ToList();
                    const int StableStatusCheckCount = 2;

                    if (queueList.Count < StableStatusCheckCount)
                    {
                        _logger.LogInformation("控制ID[{JackID}]状态数据不足({Count}/{Required})，继续等待...", 
                            regnum, queueList.Count, StableStatusCheckCount);
                        return;
                    }

                    var recentStatuses = queueList.TakeLast(StableStatusCheckCount);
                    bool isStatusConsistent = recentStatuses.All(s => s == targetStatus);

                    if (isStatusConsistent)
                    {
                        JackCurStatusEnumQueue.ClearAllSubscriptions();
                        tcs.TrySetResult(true);
                        _logger.LogInformation("控制ID[{JackID}]状态稳定达成，最终状态：{Status}",regnum, targetStatus);
                    }
                    else
                    {
                        _logger.LogDebug("控制ID[{JackID}]状态波动检测，最近{Count}次状态序列：{Statuses}", regnum, StableStatusCheckCount, string.Join(",", recentStatuses));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "控制ID[{JackID}]状态检查异常", regnum);
                    tcs.TrySetException(ex);
                }
            
        }

        public async Task<(bool successed, string msg)> Jack_Ctrl_Func(JackCtrlType isup)
        {
            var regnum = new Random().Next(100, 1000);
            var cts = new CancellationTokenSource();
            var targetStatus = GetTargetJackStatus(isup);
            var statusCheckTask = new TaskCompletionSource<bool>();

            _logger.LogInformation("顶升控制ID[{JackID}]启动，目标状态：{TargetStatus}",
                regnum, targetStatus);

            // 发送控制指令
            JsonObject keyValuePairs = new() { ["type"] = Enum.GetName(isup)?.ToString() };
            await LocalMqClientCtrl.SendMessageAsync(md_robot_jack_ctrl, keyValuePairs.ToString());

            // 状态检查回调
            void CheckStatus() => CheckStableStatus(targetStatus, regnum, statusCheckTask);
            JackCurStatusEnumQueue.AddHandler(CheckStatus);

            // 双超时机制：操作超时 + 绝对超时
            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(10), cts.Token);
            var completedTask = await Task.WhenAny(
                statusCheckTask.Task,
                timeoutTask
            );
            JackCurStatusEnumQueue.ClearAllSubscriptions();
            cts.Cancel();

            if (completedTask == statusCheckTask.Task && statusCheckTask.Task.Result)
            {
                return (true, "状态稳定达成");
            }
            _logger.LogWarning("控制ID[{JackID}]操作未完成，可能原因：{Reason}",regnum, completedTask == timeoutTask ? "操作超时" : "状态不稳定");
            return (false, completedTask == timeoutTask ? "操作超时" : "状态未稳定");
        }

        private JackStatusType GetTargetJackStatus(JackCtrlType ctrlType)
        {
            return ctrlType switch
            {
                JackCtrlType.up => JackStatusType.top,
                JackCtrlType.down => JackStatusType.bottom,
                _ => JackStatusType.defaultType
            };
        }
    }
    public enum JackCtrlType
    {
        stop = 0,
        up = 1,
        down = 2,
    }
    public enum JackStatusType
    {
        top = 0,
        middle = 1,
        bottom = 2,
        defaultType = 3,
    }
    public class MyUseQueue<T> : Queue<T>
    {
        private event Action? OnQueueChanged;
        private List<Action> _handlers = new List<Action>();

        public void AddHandler(Action handler)
        {
            OnQueueChanged += handler;
            _handlers.Add(handler);
        }

        public void ClearAllSubscriptions()
        {
            foreach (var h in _handlers)
            {
                OnQueueChanged -= h;
            }
            _handlers.Clear();
        }
        int length = 1;

        /// <summary>
        /// 初始化类的新实例，并指定长度
        /// </summary>
        /// <param name="length">长度</param>
        public MyUseQueue(int length) : base(length)
        {
            this.length = length;
        }

        /// <summary>
        /// 将对象添加到结尾处
        /// </summary>
        /// <param name="item">要添加的对象</param>
        private readonly object _lock = new object();

        public new void Enqueue(T item)
        {
            lock (_lock)
            {
                {
                    if (base.Count == length)
                        base.Dequeue();

                    base.Enqueue(item);
                    OnQueueChanged?.Invoke();
                }
            }
        }
    }
}
